import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {anyRoutes, resetRouter ,asyncRoutes,constantRoutes} from '@/router'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routes:[],
    buttons:[],
    roles:[],
    resultAsyncRoutes:[],//筛选异步router
    resultallAsyncRoutes:[]//整理全部router
  }
}
//vuex -> state
const state = getDefaultState()
//vuex -> mutations      存储state唯一方式
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  //存储token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //存储用户信息:
  SET_USERINFO:(state,userInfo)=>{
    //用户名:
    state.name = userInfo.name;
    //用户头像:
    state.avatar = userInfo.avatar;
    //菜单权限标志
    state.routes = userInfo.routes;
    //按钮权限标志:
    state.buttons = userInfo.buttons;
    //角色
    state.roles = userInfo.roles;
  },
  //最终异步路由: constantRoutes + asyncRoutes(筛选) + anyRoutes
  SET_RESULTASYNCROUTES:(state,asyncRoutes)=>{
    state.resultAsyncRoutes = asyncRoutes
    state.resultallAsyncRoutes = constantRoutes.concat(state.resultAsyncRoutes)
    //在router加入resultallAsyncRoutes
    router.addRoutes(state.resultallAsyncRoutes)
  }
}
//筛选 路由算法 递归
const computedAsyncRoutes = (asyncRoutes,routes) =>{
  return asyncRoutes.filter(item=>{
    if(routes.indexOf(item.name) != -1){
      if(item.children && item.children.length){
        item.children = computedAsyncRoutes(item.children,routes)
      }
      return true;
    }
  })
}
//vuex actions
const actions = {
  // 登录:
  async login({commit},userInfo){
    const {username,password} = userInfo;
    let result = await  login({ username: username.trim(), password: password });
    //存储token:
    if(result.code == 20000){
      commit('SET_TOKEN', result.data.token);
      setToken(result.data.token);
      return "ok"
    }else{
      return Promise.reject(new Error('false'))
    }
  },
  // 获取用户信息:  通过token:
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        commit("SET_USERINFO",data) //将用户的各个属性存储于state
        commit("SET_RESULTASYNCROUTES",computedAsyncRoutes(asyncRoutes,data.routes) )
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

